import { createRouter, createWebHashHistory } from 'vue-router'
const Layout = () => import('@/views/Layout')
// 一级分类
import TopCategory from '../views/category/index.vue'
// 二级分类
import SubCategory from '@/views/category/sub'
// 商品详情 路由
import Goods from '@/views/goods/index.vue'
// 购物车
import Cart from '@/views/cart/index.vue'

// 订单结算
const PayCheckout = () => import('@/views/member/pay/checkout')

import store from '@/store'

// 登录
const Login = () => import('@/views/login/index')
const routes = [
  // 一级路由布局容器
  {
    path: '/', component: Layout, children: [
      { path: '/', component: () => import('../views/home/index.vue') },
      { path: '/category/:id', component: TopCategory },
      { path: '/category/sub/:id', component: SubCategory },
      { path: '/product/:id', component: Goods },
      { path: '/cart', component: Cart },
      { path: '/member/checkout', component: PayCheckout }
    ]
  },
  { path: '/login', component: Login }
]
const router = createRouter({
  history: createWebHashHistory(),
  routes,
  scrollBehavior() {
    return { left: 0, top: 0 }
  }
})

// 前置导航守卫
router.beforeEach((to, from, next) => {
  // 用户信息
  const { token } = store.state.user.profile
  // 跳转去member开头的地址却没有登录
  if (to.path.startsWith('/member') && !token) {
    next({ path: '/login', query: { redirectUrl: to.fullPath } })
  }
  next()
})
export default router